#include "Socket.hpp"
#include "Protocol.hpp"
#include <ctime>
#include <unistd.h>
using namespace std;
int main(int argc, char *argv[])
{
    srand(time(nullptr));
    if (argc != 3)
    {
        cerr << "usage:" << argv[0] << "error" << endl;
        exit(0);
    }
    string serverip = argv[1];
    uint16_t serverport = htons(stoi(argv[2]));
    SockSPtr sock = std::make_shared<TcpSocket>();
    if (!sock->BuildClientSocket(serverip, serverport))
    {
        cerr << "connect error" << endl;
        exit(1);
    }
    const string opers = "+-*/%";
    while (1)
    {
        sleep(1);
        int x = rand() % 100 + 1;
        int y = rand() % 100 ;
        char oper = opers[rand() % 5];
        // 请求
        auto req = Factory::BuildRequest();
        req->Set(x, y, oper);
        // 序列化
        string reqstr;
        req->Serialize(&reqstr);
        // 增加报头
        reqstr = Encode(reqstr);
        cout << "request:" << reqstr << endl;
        // 发送
        sock->Send(reqstr);
        // 接收
        string packagestream;
        while (1)
        {
            int n = sock->Recv(&packagestream);
            if (n < 0)
                break;
            string package = Decode(packagestream);
            if (package == "")
                continue;
            else
            {
                auto resp = Factory::BuildResponse();
                resp->Deserialize(package);
                resp->PrintResult();
                cout << "-------------------------" << endl;
                break;
            }
        }
    }
    return 0;
}